﻿using System;
using Sharp.WeShare.Common;

namespace Sharp.WeShare.MP.JSSDK.Entity
{
    public class JsApiTicket : BaseRes
    {
        public string ticket { get; set; }
        public int expires_in { get; set; }

        private static object locker = new object();

        /// <summary>
        /// 获取access_token，并在获取失败后，返回失败原因。
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="accessToken">接口调用凭证</param>
        /// <param name="errmsg"></param>
        /// <returns></returns>
        public static string GetValue(string appId, string accessToken, out string errmsg)
        {
            errmsg = "";
            lock (locker)
            {
                var key = appId + "jsapi";
                var value = CacheHelper.GetValue(key);
                if (string.IsNullOrEmpty(value))
                {
                    string url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi",accessToken);
                    JsApiTicket ticket = Utils.GetResult<JsApiTicket>(url);
                    if (ticket.errcode == 0)
                    {
                        CacheHelper.Add(key, ticket.ticket, DateTime.Now.AddSeconds(ticket.expires_in / 2));
                        value = ticket.ticket;
                    }
                    else
                    {
                        errmsg = ticket.errmsg;
                    }
                }
                return value;
            }
        }
        /// <summary>
        /// 获取access_token
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static string GetValue(string appId, string appSecret)
        {
            string errmsg;
            return GetValue(appId, appSecret, out errmsg);
        }

        /// <summary>
        /// 强制刷新。用于在未知原因导致的access_ken实效的情况下，强制刷新。由于access_token的接口调用次数限制，请慎用此接口。
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="accessToken"></param>
        /// <param name="errmsg"></param>
        /// <returns></returns>
        public static string Refresh(string appId, string accessToken, out string errmsg)
        {
            errmsg = "";
            var key = appId + "jsapi";
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", accessToken);
            JsApiTicket ticket = Utils.GetResult<JsApiTicket>(url);
            if (ticket.errcode == 0)
            {
                CacheHelper.Refresh(key, ticket.ticket, DateTime.Now.AddSeconds(ticket.expires_in / 2));
            }
            else
            {
                errmsg = ticket.errmsg;
            }
            return ticket.ticket;
        }

    }
}